<template>
  <BasicForm @register="registerForm" />
</template>
<script lang="ts" setup>
  import { ref, computed, unref, toRaw, useAttrs, watchEffect, onMounted, onUnmounted } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { specFormSchema } from "./goods.data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { list as listGoodsSpec } from "../goodsSpec/spec.api"
  import { SpecProps } from "./type"
  import { useRuleFormItem } from "/@/hooks/component/useFormItem"
  import { useUserStore } from "/@/store/modules/user"

  const userStore = useUserStore()
  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register", "change"])

  const attrs = useAttrs()
  const props = defineProps(SpecProps)
  const scheme = ref<any[]>([])
  const wrapperCol = ref({
    md: { span: 24 },
    sm: { span: 24 },
  })
  const [registerForm, { setProps, resetSchema, resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    wrapperCol: wrapperCol.value,
    labelWidth: 70,
    showActionButtonGroup: false,
  })

  onUnmounted(() => {
    console.log("onUnmounted")
  })

  onMounted(async () => {
    const id = props?.spec?.specId || new Date().getTime()
    // 在同一个组件中用多个baseform会有问题, 这里定义一个随机值
    JSON.parse(JSON.stringify(specFormSchema)).forEach((e) => {
      if (e.field === "spec" || e.field === "specValue") {
        e.field = e.field + "_" + id
      }
      scheme.value.push(e)
    })
    resetSchema(toRaw(scheme.value))
    await resetFields()

    const data = {}
    data["specValue_" + id] = toRaw(props.spec.values)
    data["spec_" + id] = props.spec.specId
    console.log("data", data)
    setFieldsValue(data)

    updateSchema({
      field: "spec_" + id,
      component: "ApiSelect",
      componentProps: ({ formModel, formActionType }) => {
        return {
          optionFilterProp: "label",
          labelField: "name",
          valueField: "id",
          showSearch: true,
          api: listGoodsSpec,
          onSelect: async (value: any, option: any) => {
            console.log("option", option)

            formModel["specValue_" + id] = undefined
            updateSpecValueSchema(id, option)
          },
          onOptionsChange: async (options) => {
            if (props.spec) {
              const option = options.filter((e) => e.value === props.spec.specId)[0]
              if (option) {
                updateSpecValueSchema(id, option)
              }
            }
          },
        }
      },
    })
    setProps({ disabled: !userStore.getSelectTenant.isMainTenant })
  })

  const updateSpecValueSchema = (id, specOption) => {
    console.log("specOption", id, specOption)

    const options = specOption.valueData.split(",").map((e) => {
      return { label: e, value: e }
    })
    updateSchema({
      field: "specValue_" + id,
      componentProps: ({}) => {
        return {
          mode: "tags",
          optionFilterProp: "label",
          showSearch: true,
          options,
          onChange: (selectValue: any, _) => {
            console.log("onChange-selectValue: ", selectValue, ", specOption: ", specOption)

            // 校验是否库存为0
            // if (props.isUpdate) {
            //   const skuList = props.skuList.filter(e => e.specData && e.specData[0].specId ===  specOption.value)
            //   const totalStock = skuList.length == 0 ? 0 : skuList.flatMap(e => e.stockList).map(e => e.stock).reduce((e1, e2) => e1 + e2)
            //   console.log('specId', specOption.value, 'totalStock', totalStock);
            //   if (totalStock > 0) {
            //     createMessage.warn('需要商品所有规格的库存都为0时，才能删除规格。如需添加，请先调整库存')
            //     throw new Error('库存不为0')
            //   }
            // }
            const data = {
              ...props.spec,
              specId: specOption.value,
              values: selectValue,
              name: specOption.label,
            }
            emit("change", data)
          },
        }
      },
    })
  }

  //提交事件
  async function handleSubmit() {
    const values = await validate()
    console.log("submit data: ", values)
    emit("success")
  }
</script>
